package controller

import (
	"agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"agent-list---web-development/list/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

// 返回时间信息含TZ
func GetAllTask(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	fmt.Println(account)
	var task []model.Task
	err := DB.Where("account=? AND status=? AND endtime<?", account, 0, time.Now()).Find(&task).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试!")
		log.Println("err:", err)
		return
	}
	for _, t := range task {
		err2 := DB.Exec("UPDATE tasks SET status=? WHERE id=?", 2, t.Id).Error
		if err2 != nil {
			log.Println("err:", err)
			response.Response(ctx, http.StatusBadRequest, 422, nil, "操作失败，请重试！")
			return
		}
	}
	err1 := DB.Where("account=?", account).Order("endtime ASC").Find(&task).Error
	if err1 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试!")
		log.Println("err:", err)
		return
	}
	if len(task) == 0 {
		response.Response(ctx, http.StatusNotFound, 404, nil, "未找到相关记录!")
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功!")
}

func GetUndoTask(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.PostForm("account")
	var task []model.Task
	err := DB.Where("account=? AND status=?", account, 0).Order("starttime ASC").Find(&task).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试!")
		log.Println("err:", err)
		panic(err)
	}
	if len(task) == 0 {
		response.Response(ctx, http.StatusNotFound, 404, nil, "未找到相关记录!")
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功!")
}

func GetDoneTask(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.PostForm("account")
	var task []model.Task
	err := DB.Where("account=? AND status=?", account, 1).Order("starttime ASC").Find(&task).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试!")
		log.Println("err:", err)
		panic(err)
	}
	if len(task) == 0 {
		response.Response(ctx, http.StatusNotFound, 404, nil, "未找到相关记录!")
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功!")
}

func GetExpiredTask(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.PostForm("account")
	var task = []model.Task{}
	err := DB.Where("account=? AND status=?", account, 2).Order("starttime ASC").Find(&task).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试!")
		log.Println("err:", err)
		panic(err)
	}
	if len(task) == 0 {
		response.Response(ctx, http.StatusNotFound, 404, nil, "未找到相关记录!")
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功!")
}
